package com.example.SocialApplication.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.*;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.example.SocialApplication.HelperFactory;
import com.example.SocialApplication.R;
import com.example.SocialApplication.activity.fragments.MyOwnListFragment;
import com.example.SocialApplication.activity.fragments.MySharedListFragment;
import com.example.SocialApplication.activity.fragments.PeopleFragment;
import com.example.SocialApplication.activity.fragments.ThingsFragment;
import com.example.SocialApplication.adapters.SectionsPagerAdapter;
import com.example.SocialApplication.db.entity.ColorEntity;
import com.example.SocialApplication.db.entity.User;
import com.example.SocialApplication.service.CallServiceGetColors;
import com.example.SocialApplication.service.CallServiceGetImageById;
import com.example.SocialApplication.service.CallServiceGetThingImages;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends FragmentActivity {
    private MyPageAdapter adapter;
    private User user;
    private ViewPager pager;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    ;

    List<Fragment> fragments = Arrays.asList(new MyOwnListFragment(), new MySharedListFragment(), new Fragment(), new ThingsFragment());

    private boolean doubleBackToExitPressedOnce = false;
    private Toast exitToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        Button button = (Button) findViewById(R.id.main_layout_button_next);
        button.setVisibility(View.GONE);
//        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), fragments, new IPageTitleSetter() {
//            @Override
//            public String setTitle(int position, Locale l) {
//                switch (position) {
//                    case 0:
//                        return "МОИ СПИСКИ";
//                    case 1:
//                        return "ВСЕ СПИСКИ";
//                    case 2:
//                        return "ЛЮДИ";
//                    case 3:
//                        return "ВЕЩИ";
//
//                }
//                return null;
//            }
//        });


        user = (User) getIntent().getSerializableExtra("user");

        TextView textView = (TextView) findViewById(R.id.user_name);
        textView.setText(user.getFirstName() + " " + user.getLastName());

        final ImageView view = (ImageView) findViewById(R.id.user_avatar);
        byte[] decodedString = Base64.decode(user.getPhoto(), Base64.DEFAULT);
        Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        view.setImageBitmap(decodedByte);
//        if (user.getPhoto() != null) {
//            new GetBitmapFromStream() {
//                @Override
//                protected void onPostExecute(Bitmap bitmap) {
//                    if (bitmap != null) {
//                        view.setImageBitmap(bitmap);
//                    }
//                }
//            }.execute(user.getPhoto());
//
//        } else {
//            new GetUserAvatarService() {
//                @Override
//                protected void onPostExecute(Bitmap bitmap) {
//                    view.setImageBitmap(bitmap);
//                }
//            }.execute(user.getSocialId());
//        }

        pager = (ViewPager) findViewById(R.id.pager);
//        pager.setAdapter(mSectionsPagerAdapter);
        adapter = new MyPageAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        pager.setCurrentItem(0);

        final TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
//        tabHost.setVisibility(View.GONE);
        tabHost.setup();

        addTab(tabHost, tabHost.newTabSpec("my_lists").setIndicator(prepareTabView(this, "МОИ СПИСКИ")), new TabInfo("my_lists", new MyOwnListFragment(), savedInstanceState));
        addTab(tabHost, tabHost.newTabSpec("sll_Lists").setIndicator(prepareTabView(this, "ВСЕ СПИСКИ")), new TabInfo("sll_Lists", new MySharedListFragment(), savedInstanceState));
        addTab(tabHost, tabHost.newTabSpec("people").setIndicator(prepareTabView(this, "ЛЮДИ")), new TabInfo("people", new PeopleFragment(), savedInstanceState));
        addTab(tabHost, tabHost.newTabSpec("things").setIndicator(prepareTabView(this, "ВЕЩИ")), new TabInfo("things", new ThingsFragment(), savedInstanceState));

        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                if (tabId.equals("my_lists")) {
                    pager.setCurrentItem(0);
                } else if (tabId.equals("sll_Lists")) {
                    pager.setCurrentItem(1);
                } else if (tabId.equals("people")) {
                    pager.setCurrentItem(2);
                } else {
                    pager.setCurrentItem(3);
                }
            }
        });

        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i2) {
            }

            @Override
            public void onPageSelected(int i) {
                tabHost.setCurrentTab(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

        loadImages();
    }

    private static View prepareTabView(Context context, String text) {
        View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
        TextView textView = (TextView) view.findViewById(R.id.tabsText);
        textView.setText(text);
        return view;
    }


    private void addTab(TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
        tabSpec.setContent(new TabFactory(this));
        String tag = tabSpec.getTag();

        tabInfo.fragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.detach(tabInfo.fragment);
            ft.commit();
            getSupportFragmentManager().executePendingTransactions();
        }
        tabHost.addTab(tabSpec);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.LISTS:
                return true;
            case R.id.PEOPLE:
                return true;
            case R.id.THINGS:
                //intent = new Intent(this, ThingsActivity.class);
                //startActivity(intent);
                return true;
        }
        return true;
    }

    private class MyPageAdapter extends FragmentStatePagerAdapter {

        public MyPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = new MyOwnListFragment();
                    break;
                case 1:
                    fragment = new MySharedListFragment();
                    break;
                case 2:
                    fragment = new PeopleFragment();
                    break;
                case 3:
                    fragment = new ThingsFragment();
                    break;
            }
            return fragment;
        }

        @Override
        public int getCount() {
            return 4;
        }
    }

    private class TabInfo {
        private String tag;
        private Fragment clss;
        private Bundle args;
        private Fragment fragment;

        TabInfo(String tag, Fragment clazz, Bundle args) {
            this.tag = tag;
            this.clss = clazz;
            this.args = args;
        }
    }

    class TabFactory implements TabHost.TabContentFactory {

        private final Context mContext;

        public TabFactory(Context context) {
            mContext = context;
        }

        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
//            super.onBackPressed();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            exitToast.cancel();
            startActivity(intent);
            return;
        }
        this.doubleBackToExitPressedOnce = true;
        exitToast = createExitToast();
        exitToast.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }

    protected Toast createExitToast() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toast_layout_root));

        ImageView image = (ImageView) layout.findViewById(R.id.image);
        image.setImageResource(R.drawable.logo);
        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Для выхода нажмите \"Назад\" еще раз");
        Toast toast = new Toast(this);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        return toast;
    }

    private void loadImages() {
        new CallServiceGetThingImages() {
            @Override
            protected void onPostExecute(List<String> list) {
                new CallServiceGetImageById(MainActivity.this, list) {
                    @Override
                    protected void onPostExecute(Void aVoid) {
                        Log.i(MainActivity.class.getName(), "Images loaded");
                    }
                }.execute();
            }
        }.execute();

        new CallServiceGetColors() {
            @Override
            protected void onPostExecute(List<ColorEntity> colorEntities) {
                if (colorEntities != null) {
                    Log.i(getClass().getName(), "Save ColorEntity list, size = " + colorEntities.size());
                    for (ColorEntity entity : colorEntities) {
                        try {
                            HelperFactory.getHelper().getColorEntityDAO().create(entity);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.execute();
    }
}
